import { message } from '@/components/XtxUI'
import { useMemberStore } from '@/store'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  // https://cn.vitejs.dev/config/shared-options.html#resolve-extensions
  // 配置路由时，不要忘记补全文件.vue后缀
  routes: [
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      // 二级路由
      children: [
        {
          path: '',
          component: () => import('@/views/home/index.vue')
        },
        {
          path: 'category/:id',
          component: () => import('@/views/category/index.vue')
        },
        {
          path: 'goods/:id',
          component: () => import('@/views/goods/index.vue')
        },
        {
          path: 'cart',
          component: () => import('@/views/cart/index.vue')
        },
        // 注意路由的命名，/member/* 代表用户需要登录才能访问
        {
          path: 'member',
          component: () => import('@/views/member/sub-layout/index.vue'),
          // 三级路由
          children: [
            {
              path: '',
              component: () => import('@/views/member/home/index.vue')
            },
            {
              path: 'order',
              component: () => import('@/views/member/order/index.vue')
            }
          ]
        },
        {
          path: 'member/checkout',
          component: () => import('@/views/checkout/index.vue')
        },
        {
          path: 'member/pay/:orderId',
          component: () => import('@/views/pay/index.vue')
        },
        {
          path: 'member/pay/callback',
          component: () => import('@/views/pay/callback.vue')
        }
      ]
    },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    { path: '/login/callback', component: () => import('@/views/login/callback.vue') }
  ],
  // scrollBehavior(to, from, savedPosition) {
  //   if (savedPosition) {
  //     return savedPosition
  //   } else {
  //     return { top: 0 }
  //   }
  // }
  scrollBehavior() {
    // 始终滚动到顶部
    return { top: 0 }
  }
})

// 全局前置守卫
router.beforeEach((to) => {
  const memberStore = useMemberStore()
  // 未登录并访问“/member”开头的路径，需要跳转登录页
  if (!memberStore.isLogin && to.path.startsWith('/member')) {
    message({ type: 'warn', text: '请先登录' })
    return `/login?redirect=${to.fullPath}`
  }
})

export default router
